package com.loong.musicdemo.util.dataDeal;

import android.util.Log;

import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.model.SongList;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;


public class MusicDeal {
    private static final String MUSIC_PLAY_URL_PRE = "http://47.112.224.146:3000/song/url?id=";
    private static final String MUSIC_USEFUL_URL_PRE = "http://47.112.224.146:3000/check/music?id=";
    private static final String MUSIC_RECOMMEND_NEW_SONG_URL_PRE = "http://47.112.224.146:3000/personalized/newsong";
    private static final String MUSIC_DAILY_NEW_SONG_URL_PRE = "http://47.112.224.146:3000/top/song?type=7";
    private static final String MUSIC_SONG_LIST_URL_PRE = "http://47.112.224.146:3000/personalized?limit=6";
    private static final String MUSIC_PLAY_LIST_URL_PRE = "http://47.112.224.146:3000/playlist/detail?id=";
    private static final String MUSIC_PLAY_LIST_COMMENT_URL_PRE = "http://47.112.224.146:3000/comment/playlist?id=";
    private static final String GET_SONG_URL_PRE = "http://47.112.224.146:3000/song/detail?ids=";

    //获取每日推荐的新歌曲
    public static List<Song> getRecommendNewSongs() {
        List<Song> recommendNewSongs;
        recommendNewSongs = LitePal.findAll(Song.class);
        if (recommendNewSongs.size() != 0) { //数据库中有就直接读
            return recommendNewSongs;
        } else {  //没有就存
            String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_RECOMMEND_NEW_SONG_URL_PRE);
            try {
                JSONObject array = new JSONObject(response);
                JSONArray result = array.getJSONArray("result");
                for (int i = 0; i < 9; i++) {
                    JSONObject object = result.getJSONObject(i);
                    JSONObject s = object.getJSONObject("song");
                    JSONArray artists = s.getJSONArray("artists");
                    JSONObject artist = artists.getJSONObject(0);
                    JSONObject album = s.getJSONObject("album");
                    Song song = new Song();
                    song.setSongId(object.getString("id"));
                    song.setName(object.getString("name"));
                    song.setUseful(isUseful(song.getSongId()));
                    song.setSingerName(artist.getString("name"));
                    song.setSingerId(artist.getString("id"));
                    song.setMessage(getMusicMsg(song.isUseful()));
                    song.setPlayUrl(getMusicPlayUrl(song.getSongId()));
                    song.setPicUrl(object.getString("picUrl"));
                    song.setAlbumName(album.getString("name"));
                    song.setAlbumId(album.getString("id"));
                    song.save();
                    recommendNewSongs.add(song);
                }
                return recommendNewSongs;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return recommendNewSongs;
        }

    }

    //获取每日推荐歌曲的所有id
    public static List<String> getDailyNewSongsID() {
        List<String> newSongsId = new ArrayList<>();
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_DAILY_NEW_SONG_URL_PRE);
        try {
            JSONObject array = new JSONObject(response);
            //Log.i("info",response);
            JSONArray data = array.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                JSONObject songObject = data.getJSONObject(i);
                newSongsId.add(songObject.getString("id"));
            }
            Log.i("info", newSongsId.toString());
            return newSongsId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取音乐可用状态
    private static boolean isUseful(String id) {
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_USEFUL_URL_PRE + id);
        try {
            JSONObject result = new JSONObject(response);
            return result.getString("message").equals("ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //获取音乐的播放地址
    private static String getMusicPlayUrl(String id) {
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_PLAY_URL_PRE + id);
        try {
            JSONObject result = new JSONObject(response);
            JSONArray data = result.getJSONArray("data");
            JSONObject song = data.getJSONObject(0);
            return song.getString("url");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取音乐的图片地址
    public static String getMusicPicUrl(String id) {
        String response = HttpUtil.sendReturnOKHttpRequest(GET_SONG_URL_PRE + id);
        try {
            JSONObject result = new JSONObject(response);
            JSONArray songs = result.getJSONArray("songs");
            JSONObject song = songs.getJSONObject(0);
            JSONObject al = song.getJSONObject("al");
            return al.getString("picUrl");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取6个随机歌单的信息
    public static List<SongList> getSongList() {
        List<SongList> songLists;
        songLists = LitePal.findAll(SongList.class);
        if (songLists.size() != 0) {
            return songLists;
        } else {
            String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_SONG_LIST_URL_PRE);
            List<String> creatorInfo;
            try {
                JSONObject object = new JSONObject(response);
                JSONArray result = object.getJSONArray("result");
                for (int i = 0; i < result.length(); i++) {
                    JSONObject playList = result.getJSONObject(i);
                    SongList songList = new SongList();
                    songList.setSongListId(playList.getString("id"));
                    songList.setName(playList.getString("name"));
                    songList.setBackgroundUrl(playList.getString("picUrl"));
                    songList.setPlayCount(playList.getString("playCount"));
                    creatorInfo = getPlayListCreatorInfo(songList.getSongListId());
                    songList.setSongIds(getSongOfSongListsId(songList.getSongListId()));
                    songList.setCreatorId(creatorInfo.get(0));
                    songList.setCreatorName(creatorInfo.get(1));
                    songList.setCreatorAvatarUrl(creatorInfo.get(2));
                    songList.setCommentCount(getPlaylistCommentCount(songList.getSongListId()));
                    songList.save();
                    songLists.add(songList);
                }
                return songLists;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    //获取歌单的评论数
    public static String getPlaylistCommentCount(String songListId) {
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_PLAY_LIST_COMMENT_URL_PRE + songListId);
        try {
            JSONObject object = new JSONObject(response);
            return object.getString("total");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }

    //获取对应歌单id中所有的歌曲id
    public static List<String> getSongOfSongListsId(String songListsId) {
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_PLAY_LIST_URL_PRE + songListsId);
        List<String> ids = new ArrayList<String>();
        try {
            JSONObject array = new JSONObject(response);
            JSONObject playlist = array.getJSONObject("playlist");
            JSONArray trackIds = playlist.getJSONArray("trackIds");
            for (int i = 0; i < trackIds.length(); i++) {
                JSONObject track = trackIds.getJSONObject(i);
                ids.add(track.getString("id"));
            }
            return ids;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据歌单id获取对应歌单的创建者的信息
    public static List<String> getPlayListCreatorInfo(String songListId) {
        String response = HttpUtil.sendReturnOKHttpRequest(MUSIC_PLAY_LIST_URL_PRE + songListId);
        List<String> creatorInfo = new ArrayList<>();
        try {
            JSONObject array = new JSONObject(response);
            JSONObject playlist = array.getJSONObject("playlist");
            JSONObject creator = playlist.getJSONObject("creator");
            creatorInfo.add(creator.getString("userId"));
            creatorInfo.add(creator.getString("nickname"));
            creatorInfo.add(creator.getString("avatarUrl"));
            return creatorInfo;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据音乐的可用状态获取音乐的权限信息
    private static String getMusicMsg(boolean status) {
        return status ? "ok" : "亲爱的,暂无版权";
    }

    //获取多个歌曲的信息
    public static List<Song> getSongListByIds(List<String> ids) {
        StringBuilder idsString = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            if (!(i == ids.size() - 1))
                idsString.append(ids.get(i)).append(",");
            else
                idsString.append(ids.get(i));
        }
        String response = HttpUtil.sendReturnOKHttpRequest(GET_SONG_URL_PRE + idsString.toString());
        List<Song> songList = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray songs = object.getJSONArray("songs");
            for (int i = 0; i < songs.length(); i++) {
                Song song = new Song();
                JSONObject s = songs.getJSONObject(i);
                JSONObject ar = s.getJSONArray("ar").getJSONObject(0);
                JSONObject al = s.getJSONObject("al");
                song.setSongId(s.getString("id"));
                song.setName(s.getString("name"));
                song.setAlbumName(al.getString("name"));
                song.setSingerId(ar.getString("id"));
                song.setSingerName(ar.getString("name"));
                song.setPicUrl(al.getString("picUrl"));
//                boolean status = isUseful(ids.get(i));
                song.setUseful(true);
                song.setMessage(getMusicMsg(true));
                song.setPlayUrl(getMusicPlayUrl(ids.get(i)));
                song.setMvId(s.getString("mv"));
                songList.add(song);
            }
            return songList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return songList;
    }

    //获取单个歌曲的信息
    public static Song getSongInfoById(String id) {
        String response = HttpUtil.sendReturnOKHttpRequest(GET_SONG_URL_PRE + id);
        Song song = new Song();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray songs = object.getJSONArray("songs");
            JSONObject s = songs.getJSONObject(0);
            JSONObject ar = s.getJSONArray("ar").getJSONObject(0);
            JSONObject al = s.getJSONObject("al");
            song.setSongId(s.getString("id"));
            song.setName(s.getString("name"));
            song.setAlbumName(al.getString("name"));
            song.setSingerId(ar.getString("id"));
            song.setSingerName(ar.getString("name"));
            song.setPicUrl(al.getString("picUrl"));
            boolean status = isUseful(id);
            song.setUseful(status);
            song.setMessage(getMusicMsg(status));
            song.setPlayUrl(getMusicPlayUrl(id));
            return song;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return song;
    }

    //获取当前用户最近播放的所有音乐的id
    public static List<String> getWeekPlayRecordIds(String uid) {
        String url = "http://47.112.224.146:3000/user/record?uid=" + uid + "&type=1";
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        List<String> ids = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray weekData = object.getJSONArray("weekData");
            for (int i = 0; i < weekData.length(); i++) {
                JSONObject wd = weekData.getJSONObject(i);
                JSONObject song = wd.getJSONObject("song");
                ids.add(song.getString("id"));
            }
            return ids;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ids;
    }

}
